<template>
	<view class="wrapper-add-o">
		<!-- 收货信息 -->
		<view class="reve-info">
			<view class="title">收货信息</view>
			<view class="lists">
				<view class="item flex">
					<label>客户名称</label>
					<view class="label-content" v-if="cusType != 3">
						<uni-combox emptyTips="没有此客户.." :candidates="cusNames" placeholder="请选择客户" @input="selectCus"></uni-combox>
						<!-- <input-autocomplete class="unit-item__input" placeholder="请输入客户名称"
						:value="cusName"
						v-model='cusName'
						 highlightColor="#FF0000" :loadData="loadAutocompleteData" @selectItem="selectItemD"
						 :debounce = "1000"></input-autocomplete> -->
					</view>
					<view class="label-content" v-else>
						<view>{{cusName}}</view>
					</view>
				</view>
				<view class="item flex" v-if="cusType != 3">
					<label>联系人</label>
					<view class="label-content">
						<view class="label-content">
							<!-- <view class="area" :class="[area ?'':'placeholder']" @click="toggleTab('region')">{{area?area:'请选择收货地址'}}</view> -->
							<view>{{linkName}}</view>
						</view>	
					</view>
				</view>
				<view class="item flex" v-if="cusType != 3">
					<label>联系电话</label>
					<view class="label-content">
						<view>{{linkPhone}}</view>
					</view>
				</view>
				<view class="item flex">
					<label>收货地址</label>
					<view class="label-content">
						<view>{{adressDetail}}</view>
					</view>
				</view>
				<view class="item flex">
					<label>下单日期</label>
					<view class="label-content">
						<view class="date" :class="[orderDate ?'':'placeholder']" @click="toggleTab('orderdate')">{{orderDate?orderDate:'请选择下单日期'}}</view>
					</view>
				</view>
				<view class="item flex">
					<label>送货日期</label>
					<view class="label-content">
						<view class="date" :class="[sendDate ?'':'placeholder']" @click="toggleTab('senddate')">{{sendDate?sendDate:'请选择送货日期'}}</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 商品信息 -->
		<view class="goods-info">
			<view class="title">商品信息</view>
			<view class="table-c">
				<!-- <v-table :columns="columnsOperate" :list="dataOperate" @delete="deleteFn" @edi="ediFn"></v-table> -->
				<t-table v-if="update">
					<t-tr >
						<t-th :fixedWidth="140">操作</t-th>
						<t-th :fixedWidth="160">商品名称</t-th>
						<t-th :fixedWidth="94">单位</t-th>
						<t-th :fixedWidth="100">数量</t-th>
						<t-th class="flex-1">小计（元）</t-th>
					</t-tr>
					<t-tr v-for="(item,index) in dataOperate" :key="index">
						<t-td :fixedWidth="140">
							<!-- <button type="primary" class="c-mini" @click="deleteFn(index)">+</button>
							<button type="primary" class="c-mini del" @click="ediFn(index)">-</button> -->
							<uni-icons type="tianjia" size="20" color="#277ec3" style="margin-right: 16rpx;" @click="togglePopup('center', 'tip')"></uni-icons>
							<uni-icons type="jian" size="20" color="#277ec3" @click="deleteFn(index)"></uni-icons>
						</t-td>
						<t-td :fixedWidth="160">{{ item.goodsText }}</t-td>
						<!-- <t-td :fixedWidth="94">{{ item.unit }}</t-td> -->
						<t-td :fixedWidth="94">{{ item.specsText }}</t-td>
						<t-td :fixedWidth="100" @click="modify('tips',item)">{{ item.sendNum }}</t-td>
						<t-td class="flex-1">{{ (item.sendNum)*item.yhPrice | fixedT }}</t-td>
					</t-tr>
				</t-table>
			</view>
		</view>
		<!--订单提交 -->
		<view class="button">
			<button type="primary" @click="overBook">提交订单</button>
		</view>
		<!-- 添加商品选择 -->
		<uni-popup v-if="tipShow" ref="showtip" :animation="false" :type="type">
			<view class="uni-tip">
				<view class="hd">
					<view class="tit">添加商品</view>
					<!-- <view>
						<uni-icons type="guanbi1" size="24" color="#fff" @click="cancel('tip')"></uni-icons>
					</view> -->
				</view>
				<view class="bd">
					 <scroll-view  scroll-y="true" class="scroll-Y">
						<checkbox-group class="flex" @change="checkboxChange">
							<label class="flex" v-for="item in goodLists" :key="item.value">
								<view>
									<checkbox :value="item.goodsId" :checked="item.checked" />
								</view>
								<view>{{item.goodsText}}</view>
							</label>
						</checkbox-group>
					</scroll-view>	
				</view>
				<view class="btns">
					<button type="primary" size="mini" @click="addG">确定</button>
					<button type="default" size="mini" @click="cancel('tip')">取消</button>
				</view>
				
			</view>
		</uni-popup>
		<!-- 修改商品数量 -->
		<uni-popup ref="showtips" type="center">
			<view class="uni-tips">
				<view class="hd flex">
					<view>请输入</view>
					<view>
						<uni-icons type="guanbi1" size="24" color="#fff" @click="cancel('tips')"></uni-icons>
					</view>
				</view>
				<view class="bd flex">
					<view class="item flex">
						<view class="label">数量:</view>
						<view class="ipt">
							<!-- <input type="number" v-model.trim="tempChangeNum" /> -->
							<uni-number-box :value="tempChangeNum" @change="setChangeNum" />
						</view>
					</view>
					<view class="btns">
						<button type="primary" size="mini" @click="changeNum('tips')">确定</button>
						<button type="default" size="mini" @click="cancel('tips')">取消</button>
					</view>
				</view>
			</view>
		</uni-popup>
		<!-- 下单日期选择 -->
		<w-picker
			mode="date" 
			startYear="2017" 
			endYear="2030"
			defaultVal="2019-10-31"
			:current="true" 
			@confirm="onConfirm"
			:disabledAfter="false"
			ref="orderdate" 
			themeColor="#f00"
		></w-picker>
		<!-- 送货日期选择 -->
		<w-picker
			mode="date" 
			startYear="2017" 
			endYear="2030"
			:defaultVal="defaultSendDate"
			:current="false" 
			@confirm="onConfirm"
			:disabledAfter="false"
			ref="senddate" 
			themeColor="#f00"
		></w-picker>
	</view>
</template>

<script>
	import {
	  mapState
	 } from 'vuex'
	import tTable from '@/components/t-table/t-table.vue';
	import tTh from '@/components/t-table/t-th.vue';
	import tTr from '@/components/t-table/t-tr.vue';
	import tTd from '@/components/t-table/t-td.vue';
	import uniIcons from '@/components/uni-icon/uni-icon.vue'
	import wPicker from "@/components/w-picker/w-picker.vue";
	import Request from '@/request/request.js'
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import uniCombox from '@/components/uni-combox/uni-combox.vue'
	import dayjs from '@/common/dayjs.min.js'
	import uniNumberBox from '@/components/uni-number-box/uni-number-box.vue'
	export default {
		components: {
			tTable,
			tTh,
			tTr,
			tTd,
			uniIcons,
			wPicker,
			uniPopup,
			uniCombox,
			uniNumberBox
		},
		filters:{
			fixedT(value){
				if (!value) return ''
				return value.toFixed(2)
			}
		},
		computed:{
		  ...mapState(['cusType','userInfo','customerInfo'])
		 },
		data() {
			
			return {
				type:'',//弹出框位置
				toggleType:'',
				//自定义操作列
				dataOperate: [{}],
				customers:[],//新增订单代下单客户集合
				cusNames:[],//客户姓名集合
				customerId:'',//选中的客户id
				goodLists:[],//商品集合选中新增
				cusName:'',//客户名称
				linkName:'',//联系人
				linkPhone:'',
				adressDetail:'',//收货地址
				orderDate:dayjs().format('YYYY-MM-DD'),//下单日期
				defaultSendDate:dayjs().add(1, 'day').format('YYYY-MM-DD'),//默认送货日期
				sendDate:dayjs().add(1, 'day').format('YYYY-MM-DD'),//送货日期
				addGoods:[],//新增商品
				tipShow:false,
				tempChangeNum:'',//数量修改中间变量
				modifyItem:{},//记录需要修改的商品
				update:true,//更新页面数据
				flag:true,
				lastTime:0,//记录按钮上次点击时间
			}
		},
		onLoad() {
			if(this.cusType == 3){//客户自己下单
				console.log(this.customerInfo)
				this.cusName = this.customerInfo.name
				this.customerId = this.customerInfo.id
				this.checkAllowOrder()
				this.adressDetail = this.customerInfo.fullAddress
				this.getDefaultGoods(this.customerId)
				this.getGoodLists(this.customerId)
			}else{//代下单
				this.getCustorm()
			}	
			// this.getGoodLists()
		},
		methods: {
			checkAllowOrder(){
				/* 判断是否货款超期可以继续下单 */
				Request({url:'order/checkBill',data:{customerId:this.customerId}})
				  .then(res => {
					  if(res.code != 0){
						  uni.showModal({
						      title: '提示',
						      content: res.msg,
							  showCancel:false,
						      success: function (res) {
						          if (res.confirm) {
						             uni.navigateBack({
						             	
						             })
						          } else if (res.cancel) {
						              console.log('用户点击取消');
						          }
						      }
						  });
					  }
				  }).catch(err => {})
				
			},
			getCustorm(){
				//获取已审核客户名称列表
				Request({url:'customer/loadAuditedCustomers'})
				 .then(res => {
					 if(res.code == 0){
						this.customers = res.data
						 this.cusNames = this.customers.map(item => { 
							 let obj = {}
							 obj.label = item.name
							 obj.id = item.id
							 return obj
						 })
					 }
				 }).catch(err =>{})
			},
			getGoodLists(id){
				//获取新增商品列表
				Request({url:`order/loadLatestGoods/${id}`,method:'GET'})
				.then(res => {
					if(res.code == 0){
						this.goodLists = res.data.map(item =>{
							item.goodsId = String(item.goodsId)
							return item
						})
					}
				})
			},
			selectCus(e){
				//选中的客户名称	
				if(e.id){
					this.customerId = e.id
					this.cusName = e.label
					//如果存在id 说明有此客户资料
					this.checkAllowOrder()
					this.getCusInfo(e.id)
					this.getDefaultGoods(e.id)
					this.getGoodLists(e.id)
				}
				
			},
			getCusInfo(id){
				//根据id 获取客户信息
				Request({url:`customer/getCustomerById/${id}`,method:'GET'})
				.then(res =>{
					if(res.code == 0){
						this.linkName = res.data.linkMan
						this.linkPhone = res.data.linkPhone
						this.adressDetail = res.data.province + res.data.city + res.data.district + res.data.address
					}
				})
			},
			getDefaultGoods(id){
				//根据id 获取客户默认商品
				Request({url:`order/loadOrderDetailsByCustomer/${id}`,method:'GET'})
				.then(res =>{
					console.log('商品信息',res);
					if(res.code == 0){
						if(res.data&&res.data.length >= 1){
							this.dataOperate = res.data
						}else{
							this.dataOperate = [{}]
						}
					}
				})
			},
			deleteFn(index) {
				let _this = this
				if(this.dataOperate.length == 1){
					uni.showToast({
					    title: '请至少保留一种商品!',
						icon:'none',
					    duration: 2000
					})
					return
				}
				uni.showModal({
				    title: '提示',
				    content: '确定删除此商品?',
				    success:  (res) => {
				        if (res.confirm) {
				            this.dataOperate.splice(index,1)
				        } else if (res.cancel) {
				            console.log('用户点击取消');
				        }
				    }
				})
			},
			toggleTab(str){
				// #ifdef APP-PLUS
				plus.key.hideSoftKeybord()
				// #endif
				this.toggleType = str
				this.$refs[str].show();
			},
			onConfirm(val){
				switch(this.toggleType){
					case 'orderdate':
						this.orderDate = val.result;
						break
					case 'senddate':
						this.sendDate = val.result;
						break;
				}
			},
			togglePopup(type, open,item) {
				if(!this.cusName){//没有选择客户不能新增商品
					uni.showToast({
					    title: '请选择客户!',
						icon:'none',
					    duration: 2000
					})
					return
				}
				this.tipShow = true
				this.goodLists.forEach(item =>{
					item.checked = false
				})
				this.type = type
				this.$nextTick(() => {
					this.$refs['show' + open].open()
				})
			},
			modify(open,item){
				this.modifyItem = item
				this.tempChangeNum = this.modifyItem.sendNum || 0
				this.$nextTick(() => {
					this.$refs['show' + open].open()
				})
			},
			setChangeNum(val){
				this.tempChangeNum = Number(val)
			},
			cancel(type) {
				
				this.$refs['show' + type].close()
				if(type == 'tip'){
					this.tipShow = false
				}
			},
			changeNum(type){
				//页面数据不能及时更新
				this.update = false
				this.update = true
				this.modifyItem.sendNum = this.tempChangeNum
				// this.$set(this.modifyItem,'sendNum',this.tempChangeNum)
				this.$refs['show' + type].close()
			},
			checkboxChange(e){
				let tempArr = e.detail.value
				this.goodLists.forEach(item => {
					if(tempArr.includes(String(item.goodsId))){
						this.$set(item,'checked',true)
					}else{
						this.$set(item,'checked',false)
					}
				})
			},
			addG(){
				
				if(this.selectGoods().length > 0){
					if(this.dataOperate.length == 1 && !this.dataOperate[0].goodsText){
						//说明没有默认商品
						this.dataOperate = this.selectGoods()
					}else{
						this.dataOperate.push(...this.selectGoods())
					}
				}
				this.cancel('tip')
			},
			selectGoods(){
			  return this.goodLists.filter(item =>{
				  item.sendNum = item.sendNum || item.num 
				  item.yhPrice = item.yhPrice || item.discountPrice
				  return item.checked == true
			  })
			},
			getParams(){
				let params = {
					customerId:this.customerId,
					sendDate:this.sendDate,
					orderDate:this.orderDate
				}
				params.orderDetails = this.dataOperate.map(item =>{
							let obj = {}
							obj.goodsId = item.goodsId
							obj.yhPrice = item.yhPrice
							obj.sendNum = item.sendNum
							obj.totalMoney = (item.yhPrice*item.sendNum).toFixed(2)
							return obj
						})
				return params
			},
			subOrder(params){
				
				Request({url:'order/addSave',data:params})
					.then(res =>{
						if(res.code == 0){
							uni.showToast({
							    title: '订单提交成功!',
							    duration: 1500
							})
							setTimeout(() =>{
								uni.navigateBack({
									
								})
							},1500)
						}
					}).catch(err =>{})
			},
			preOrder(){
				Request({url:`order/checkOrder/${this.customerId}`,method:'GET'})
				 .then(res =>{
					 if(res.code == 0){
						 if(res.msg){
							 uni.showModal({
								 title: '温馨提示',
								 content: res.msg.replace(/<br\/>/g,''),
								 success:  (res) => {
									 if (res.confirm) {
										this.subOrder(this.getParams())
									 } else if (res.cancel) {
										 console.log('用户点击取消');
									 }
								 }
							 });
						 }else{
							 this.subOrder(this.getParams())
						 }
					 }
					 
				 }).catch(err =>{})
			},
			overBook(){	
				if(!this.cusName){
					uni.showToast({
					    title: '请先添加客户!',
						icon:'none',
					    duration: 2000
					})
					return
				}
				if(!this.sendDate){
					uni.showToast({
					    title: '请先添加送货日期!',
						icon:'none',
					    duration: 2000
					})
					return
				}
				let currentTime = new Date().getTime()
				if(currentTime - this.lastTime < 1000) return//两次按钮点击时间间隔至少1S
				this.lastTime = currentTime
				this.preOrder()
				// this.subOrder(this.getParams())
			}
		}
	}
</script>

<style lang="less" scoped>
	@bottomColor: #c0c4cc;
.wrapper-add-o{
	min-height: 100%;
	background-color: #FFFFFF;
	.reve-info{
		.title{
			height: 88rpx;
			line-height: 88rpx;
			background-color: rgba(238, 238, 238, 1);
			padding: 0 40rpx;
			&::before{
				content: "*";
			}
		}
		.lists{
			.item{
				min-height: 80rpx;
				padding: 12rpx 30rpx;
				align-items: center;
				border-bottom: 2rpx solid @bottomColor;
				label{
					width: 200rpx;
					flex-shrink: 0;
				}
				.label-content{
					flex: 1;
						
					.date,.area{
						height: 68rpx;
						line-height: 68rpx;
					}
					.placeholder{
						color: grey;
					}
				}
			}
		}
	}
	.goods-info{
		margin-bottom: 20rpx;
		.title{
			height: 88rpx;
			line-height: 88rpx;
			background-color: rgba(238, 238, 238, 1);
			padding: 0 40rpx;
			&::before{
				content: "*";
			}
		}
		.table-c{
			padding: 20upx;
			.flex-1{
				flex:1
			}
			.c-mini{
				background-color:red;
				line-height: 1.2;
				padding-left: 8rpx;
				padding-right: 8rpx;
				&.del{
					padding-left: 14rpx;
					padding-right: 14rpx;
				}
			}
			t-td{
				button{
					display: inline-block;
					width: 46rpx;
					height: 46rpx;
					line-height: 46rpx;
					text-align: center;
					&+button{
						margin-left: 6rpx;
					}
				}
			}
			
		}
	}
	.button{
		padding: 30rpx 30rpx 80rpx;
	}
	/* 提示窗口 */
	.uni-tip {
		/* #ifndef APP-NVUE */
		display: flex;
		flex-direction: column;
		/* #endif */
		// padding: 15px;
		width: 290px;
		background-color: #fff;
		border-radius: 10px;
		overflow: hidden;
		.hd{
			height: 80rpx;
			background: #1784da;
			font-size: 28rpx;
			color: #fff;
			position: relative;
			text-align: center;
			line-height: 80rpx;
		}
		.bd{
			padding: 40rpx 60rpx 0;
			.scroll-Y{
				width: 100%;
				max-height: 400rpx;
			}
			checkbox-group{
				flex-wrap: wrap;
				label{
					flex:50%;
					margin-bottom: 16rpx;
				}
				checkbox{
					transform: scale(.7);
				}
			}
			
		}
		.btns{
			padding: 20rpx 0 40rpx;
			text-align: center;
			button[type=primary]{
				background-color:#1784da ;
			}
			button[size=mini]{
				padding: 0 30rpx;
			}
			button+button{
				margin-left: 24rpx;
			}
		}
	}
	/* 数量修改窗口 */
	.uni-tips {
		/* #ifndef APP-NVUE */
		display: flex;
		flex-direction: column;
		/* #endif */
		// padding: 15px;
		width: 290px;
		background-color: #fff;
		border-radius: 10px;
		overflow: hidden;
		.hd{
			height: 80rpx;
			background: #1784da;
			justify-content: space-between;
			align-items: center;
			font-size: 28rpx;
			color: #fff;
			padding:0 20rpx 0 40rpx;
		}
		.bd{
			flex-direction: column;
			padding: 40rpx;
			.item{
				align-self: center;
				align-items: center;
				margin-bottom: 30rpx;
				.label{
					width: 140rpx;
					padding-right: 16rpx;
					text-align: right;
				}
				.ipt{
					// width: 280rpx;
					height: 70rpx;
					// border: 1px solid #C0C0C0;
					// text-align: center;
					display: flex;
					align-items: center;
					// padding: 16rpx 0;
				}
			}
			.btns{
				text-align: center;
				button[type=primary]{
					background-color:#1784da ;
				}
				button[size=mini]{
					padding: 0 30rpx;
				}
				button+button{
					margin-left: 24rpx;
				}
			}
		}
	}
	
}

</style>
